package br.com.projeto.web.vraptor.controllers;

import static br.com.caelum.vraptor.view.Results.page;
import javassist.NotFoundException;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.validator.Validations;
import br.com.caelum.vraptor.view.Results;
import br.com.projeto.model.EquipeModel;
import br.com.projeto.model.HistoricoModel;
import br.com.projeto.model.UsuarioModel;
import br.com.projeto.model.entities.Usuario;
import br.com.projeto.web.vraptor.componentes.SessionUser;

@Resource
public class MainController {

	private Result result;
	private SessionUser session;
	private UsuarioModel usuariosModel;
	private EquipeModel equipesModel;
	private HistoricoModel historicoModel;
	private Validator validator;

	public MainController(Result result, SessionUser session,
			UsuarioModel usuariosModel,
			EquipeModel equipesModel, HistoricoModel historicoModel, Validator validator) {
		this.result = result;
		this.session = session;
		this.usuariosModel = usuariosModel;
		this.equipesModel = equipesModel;
		this.historicoModel = historicoModel;
		this.validator = validator;
	}

	@Get
	@Path("/login")
	public void login() {
	}

	@Post
	@Path("/login")
	public void login(final Usuario usuario) {

		try {
			
			validator.checking(new Validations() {{
				that(!usuario.getEmail().isEmpty(), "usuario.email","usuario.email.branco");
				that(!usuario.getSenha().isEmpty(), "usuario.senha","usuario.senha.branco");
			}});
			
			validator.onErrorUse(page()).of(MainController.class).login();
			
			Usuario loaded = this.usuariosModel.autenticar(usuario);

			session.setUsuario(loaded);
			session.setEquipe(loaded.getEquipe());
			result.use(Results.logic()).redirectTo(MainController.class).home();

		} catch (NotFoundException e) {
			result.use(Results.logic()).redirectTo(MainController.class).login();

		}

	}

	@Get
	@Path("/")
	public void home() {

		result.include("historicoGeral", this.historicoModel.pesquisar(session.getEquipe(), null));
		
		if(this.session.getProjeto() != null)
			result.include("historicoProjeto", this.historicoModel.pesquisar(session.getEquipe(), session.getProjeto()));
		
		result.include("projetos", this.equipesModel.obterProjetos(session
				.getEquipe()));
	}


	@Get
	@Path("/sair")
	public void logout() {
		this.session.setEquipe(null);
		this.session.setUsuario(null);
		this.session.setProjeto(null);

		result.use(Results.logic()).redirectTo(MainController.class).login();
	}
}
